<?php

namespace app\common\model;

use think\Model;

/**
 * 开支明细
 */
class ExpenseRecords extends Model
{

    // 表名,不含前缀
    protected $name = 'expense_records';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];

    public function getDetailsAttr($value)
    {
        if (empty($value)) {
            return [];
        }
        $value = json_decode($value, true);
        foreach ($value as &$item) {
            $arr = [];
            foreach ($item['images'] as $img) {
                $arr[] = cdnurl($img,true);
            }
            $item['images_text'] = $arr;
        }
        return $value;
    }


    //编辑开支
    public static function expenseEdit($params)
    {
        $user = User::info();
        $id = 0;
        extract($params);
        $price = 0;
        foreach ($details as $item){
            $price = bcadd($price,$item['fee'],2);
        }
        //id 不存在，执行添加
        if (!isset($id) || !$id) {
            $edit = self::create([
                'user_id'       => $user->id,
                'date'          => $date,
                'price'         => $price,
                'details'       => json_encode($details,JSON_UNESCAPED_UNICODE),
            ]);
        }else{
            $edit = self::update([
                'user_id'       => $user->id,
                'date'          => $date,
                'price'         => $price,
                'details'       => json_encode($details,JSON_UNESCAPED_UNICODE),
                'id'            => $id
            ]);
        }
        return $edit;
    }

    //列表查询
    public static function getLists($params)
    {
        $user = User::info();
        $starttime = '';
        $endtime = '';
        extract($params);
        $where['user_id'] = $user->id;
        if (isset($starttime) && $starttime && isset($endtime) && $endtime) {
            $endtimeNext = date('Y-m-d',strtotime($endtime. '+1 day'));
            $where['date'] = ['between', [$starttime,$endtimeNext]];
        }
        if (isset($keywords) && $keywords) {
            $where['details'] = ['like','%'.$keywords.'%'];
        }
        return self::where($where)->order('createtime desc')->paginate(10);
    }

}
